<?php
/**
 * Merge accounts into one list, eg.
 * user[LocalAccount]{0..2}, user[OpenidAccount]{0..1} => 
 *  - a[0].type = local
 *  - a[1].type = local
 *  - a[2].type = local
 *  - a[3].type = openid
 *  - a[4].type = openid
 */
function merge_accounts($user) {
  $result = array();
  foreach ($user as $name => $accounts) {
    if (preg_match('/(.+)Account$/', $name, $matches)) {
      foreach ($accounts as $account) {
        $account['type'] = strtolower($matches[1]);
        $result[] = $account;
      }
    }
  }
  return $result;
}
?><div class="title">
  <h4><?php echo $is_own ? 'Deine' : "{$user['User']['name']}s"; ?> Konten</h4>
</div> <!-- /title -->

<p>Dein Konto hat folgende Verknüpfungen. Du kannst es mit weiteren <?php echo $html->link('Sozialen Netzwerken', array('controller' => 'users', 'action' => 'login')); ?> verbinden.</p>        
<ul class="ul-list nomb">
<?php
foreach (merge_accounts($user) as $user_account) {
?>
  <li>
<?php
$model_name = ucfirst($user_account['type']) . 'Account';
$controller_name = $user_account['type'] /* . '_accounts' */;

if ($user_account['type'] == 'local') {
  $title = $user_account['username'];
}
else
if ($user_account['type'] == 'openid') {
  $url = parse_url($user_account['identity_url']);
  $title = 'OpenID bei ' . $url['host'];
}
else
if ($user_account['type'] == 'twitter') {
  $title = $user_account['screen_name'] . ' bei twitter.com';
}

$ops = '';

// only local accounts can be edited 
if ($model_name == 'LocalAccount') {
  ob_start();
?>
    <div class="edit"><a href="#" class="ico-edit">bearbeiten</a>
      <?php echo $form->create('LocalAccount', array('url' => array('controller' => 'local', 'action' => 'edit', $user_account['id']), 'autocomplete' => 'off')); ?>
        <div class="title"><h4>Konto bearbeiten</h4></div>
        <?php echo $form->input('username', array('label' => 'Nutzername', 'value' => $user_account['username'])); ?>
        <?php echo $form->input('password', array('label' => 'Kennwort')); ?>
        <?php echo $form->input('password2', array('type' => 'password', 'label' => 'Kennwort (wiederholt)')); ?>
      <?php echo $form->end('Speichern'); ?>
    </div>
<?php
  $ops .= ob_get_clean();
}

// can't delete account user is logged in with
if (!isset($account[$model_name]) || $account[$model_name]['id'] != $user_account['id']) { 
  $ops .= $html->link('löschen', array('controller' => $controller_name, 'action' => 'delete', $user_account['id']), array('class' => 'ico-delete'), /*confirm*/'Wirklich löschen?');

}

if ($ops) {
  echo '    <span class="f-right">', $ops, '</span>';
}
?>
    <span class="date"><?php echo strftime('%d.%m.%Y', $user_account['created']); ?></span> <strong><?php echo $title; ?></strong></li>
<?php
}
?>
</ul>
